import React from 'react';
import { Button, Row, Col, Card, Descriptions, Tooltip } from 'antd';
import echarts from 'echarts';
import services from '../../../../services/api';
import CommonListsIndex from '../../../../components/CommonLists/index';
import List from './list';
import CodeLabel from '../../../../components/CodeLabel';
import Map from '../../../../components/Chart/Map';

class DevicePortraitIndex extends CommonListsIndex {
  constructor(props) {
    super(props);
    this.api = 'devicePortrait';
    this.model_width = 600;
    this.listsComponent = List;
    this.id = decodeURIComponent(props.match.params.id);
    this.state = {
      ...this.state,
      ipRelation: {},
      tokenRelation: {},
      device: {},
      activeKey: ''
    };
    this.queryTableParams = {
      keyword: this.id
    };
    this.chartToken = null;
    this.chartIp = null;
    this.initQueryPanigation = {
      // 初始化分页参数
      current_page: 1,
      page_size: 5
    };
    this.queryPanigation = this.initQueryPanigation; //分页参数
  }
  async componentDidMount() {
    await this.getDeviceInfo();
    await this.getStatistics();
    this.freshQueryList();
  }

  getStatistics = () => {
    services.devicePortrait
      .statistics({
        keyword: this.id
      })
      .then(res => {
        if (res.code === 0) {
          let data = res.data;

          const tokenRelation = {
            name: `设备指纹(${data.token ? data.token.length : 0})`,
            value: this.state.device.dev_id,
            children: (data.token || []).map(it => {
              return { name: 'Token', value: it };
            })
          };
          const ipRelation = {
            name: `设备指纹(1)`,
            value: this.state.device.dev_id,
            children: (data.ip || []).map(it => {
              const item = {
                name: `IP(${it.dev_id ? it.dev_id.length : 0})`,
                value: it.ip,
                children: (it.dev_id || []).map(it2 => {
                  return { name: '设置指纹', value: it2 };
                })
              };
              return item;
            })
          };

          this.drawRelation(tokenRelation, 'token');
          this.setState({
            ipRelation,
            tokenRelation,
            location: data.location
          });
        }
      });
  };
  getDeviceInfo = () => {
    services.devicePortrait
      .deviceInfo({
        keyword: this.id
      })
      .then(res => {
        if (res.code === 0) {
          this.setState({
            device: res.data
          });
        }
      });
  };
  getColumns = () => {
    return [
      {
        title: '时间',
        key: 'req_time',
        dataIndex: 'req_time',
        ellipsis: true,
        render: text => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        }
      },
      {
        title: '设备信息',
        key: 'field_id',
        dataIndex: 'field_id',
        render: (text, record) => {
          let txt = record.brand + '-' + record.model;
          return <Tooltip title={txt}>{txt}</Tooltip>;
        }
      },
      {
        title: '访问方式',
        key: 'access_way',
        dataIndex: 'access_way'
      },
      {
        title: '操作系统',
        key: 'os',
        dataIndex: 'os'
      },
      {
        title: '网络信息',
        key: 'network_type',
        dataIndex: 'network_type'
      },
      {
        title: '行为',
        key: 'risk_level',
        dataIndex: 'risk_level',
        render: text => {
          return <CodeLabel code={'risk_level'} value={text} />;
        }
      }
    ];
  };

  drawRelation = (data, activeKey) => {
    this.setState({ activeKey });
    let layout = (data && data.children && data.children.length < 3) || activeKey === 'ip' ? 'orthogonal' : 'radial';
    let option = {
      tooltip: {
        trigger: 'item',
        triggerOn: 'mousemove'
      },
      series: [
        {
          data: [data],

          type: 'tree',
          label: {
            show: true,
            position: 'bottom',
            rotate: 0,
            fontSize: 8,
            formatter: '{b}\n{c}'
          },
          itemStyle: {
            borderWidth: 0
          },
          leaves: {
            label: {
              formatter: '{b}\n{c}'
            }
          },
          tooltip: {
            formatter: '{b}<br/>{c}'
          },
          layout: layout,
          symbol: 'circle',
          symbolSize: 30,
          initialTreeDepth: 2,
          animationDurationUpdate: 750,
          roam: true
        }
      ]
    };
    if (activeKey === 'token') {
      this.chartToken && this.chartToken.clear();
      this.chartToken = null;
      this.chartToken = echarts.init(this.refs.relation);
      this.chartToken.setOption(option);
    } else {
      this.chartIp && this.chartIp.clear();
      this.chartIp = null;
      this.chartIp = echarts.init(this.refs.relation);
      this.chartIp.setOption(option);
    }
  };

  render() {
    const ListsComponent = this.listsComponent;
    const { device } = this.state;
    return (
      <div>
        <Row type='flex' justify='start' gutter={20}>
          <Col span={9} style={{ marginBottom: '20px' }}>
            <Card title='设备信息' bordered={false} style={{ height: 360 }}>
              <Descriptions column={1}>
                <Descriptions.Item label='最后请求时间'>{device.req_time}</Descriptions.Item>
                <Descriptions.Item label='行为属性'>
                  <CodeLabel code={'risk_level'} value={device.risk_level}></CodeLabel>
                </Descriptions.Item>
                <Descriptions.Item label='设备指纹'>{device.dev_id}</Descriptions.Item>
                <Descriptions.Item label='操作系统'>{device.os}</Descriptions.Item>
                <Descriptions.Item label='访问方式'>{device.access_way}</Descriptions.Item>
                <Descriptions.Item label='网络信息'>{device.network_type}</Descriptions.Item>
              </Descriptions>
            </Card>
          </Col>
          <Col span={15} style={{ marginBottom: '20px' }}>
            <Card title='历史请求' bordered={false} style={{ height: 360 }}>
              <ListsComponent
                {...this.state}
                rowKey={(record, index) => index}
                columns={this.getColumns()}
                onChangePagination={this.onChangePagination}
                showSizeChanger={false}
                // scroll={{ y: 240 }}
              />
            </Card>
          </Col>
          <Col span={9}>
            <Card title='近七天常用地' bordered={false} style={{ height: 401 }}>
              {this.state.location && this.state.location.length > 0 && <Map location={this.state.location} />}
            </Card>
          </Col>
          <Col span={15}>
            <Card title='近七日关联信息' bordered={false} style={{ height: 401 }}>
              <Row type='flex' justify='end'>
                <Col span={18}>
                  <div ref='relation' style={{ width: '100%', height: '300px' }}></div>
                </Col>
                <Col span={6}>
                  <Row type='flex' justify='end'>
                    <Col span={24}>
                      <Descriptions column={1} bordered={true} size={'small'}>
                        <Descriptions.Item
                          label='关联token'
                          className={this.state.activeKey === 'token' ? 'active' : ''}
                        >
                          <Button type='link' onClick={this.drawRelation.bind(this, this.state.tokenRelation, 'token')}>
                            {this.state.tokenRelation.children && this.state.tokenRelation.children.length}
                          </Button>
                        </Descriptions.Item>
                        <Descriptions.Item label='关联Ip' className={this.state.activeKey === 'ip' ? 'active' : ''}>
                          <Button type='link' onClick={this.drawRelation.bind(this, this.state.ipRelation, 'ip')}>
                            {this.state.ipRelation.children && this.state.ipRelation.children.length}
                          </Button>
                        </Descriptions.Item>
                      </Descriptions>
                    </Col>
                  </Row>
                </Col>
              </Row>
            </Card>
          </Col>
        </Row>
      </div>
    );
  }
}

export default DevicePortraitIndex;
